'use strict';
const { guid } = require('../utils/util');
const namespace = require('./namespace');
const request = require('request');
const OSS = require('ali-oss');
const ossUploadService = require('../service/ossUploadService');

const ossClient = new OSS({
  accessKeyId: 'LTAITldlbkDhCEVv',
  accessKeySecret: 'x7hE3GZFzmJkvkjdbWu9lkp78hoq6A',
  bucket: 'gjbhz',
  endpoint:'oss-cn-hangzhou-internal.aliyuncs.com'
});

const RPCClient = require('@alicloud/pop-core').RPCClient;
const initVodClient = (accessKeyId, secretAccessKey) => {
    var regionId = 'cn-shanghai';   // 点播服务接入区域
    var client = new RPCClient({
        accessKeyId: accessKeyId,
        secretAccessKey: secretAccessKey,
        endpoint: 'http://vod.' + regionId + '.aliyuncs.com',
        apiVersion: '2017-03-21'
    });
    return client;
};

String.prototype.padLeft =
Number.prototype.padLeft = function (total, pad) {
    return (Array(total).join(pad || 0) + this).slice(-total);
};

module.exports = function (app) {

  app.get(`${namespace.root}/uploadToOss`, async function (req, res) {
    let accessToken = req.query.accessToken;
    let mediaId = req.query.mediaId; // 微信多媒体文件id
    let now = new Date();
    let year = now.getFullYear().padLeft(4);
    let month = (now.getMonth() + 1).padLeft(2);
    let day = now.getDate().padLeft(2);
    let path = 'file/' + year + '/' + month + day + '/';
    
    let destPath = `${path}${guid()}.jpg`; // OSS文件路径
    let wxReq = request(`http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=${accessToken}&media_id=${mediaId}`);
    //console.log(`http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=${accessToken}&media_id=${mediaId}`);
    var startTime = new Date().getTime();
    console.log('start:');
    wxReq.on('response', async (response) =>  {
      console.log('read_start:' + (new Date().getTime() - startTime));
      // request的响应结果response可以作为读取流传给ossClient
        const result = await ossClient.putStream(destPath, response, { timeout: 80 * 60 * 1000 });
        //console.log('图片上传阿里云结果', result);
        console.log(result);
        res.status(200).json({
          url:'https://gjbhz.oss-cn-hangzhou.aliyuncs.com/' + result.name
        });
    });
  });


  app.get(`${namespace.root}/getOssToken`, function(req, res) {
    const result = ossUploadService.getOssToken(req, res);
    if (result) {
      res.json({
        code: 100,
        data: result
      });
    }
  });

  //取得上传视频凭证
  app.get(`${namespace.root}/getUploadOssVoucher`, function(req, res) {
    var filename = req.query.filename;
    var filenames = filename.split('.');
    var suffix = filenames[filenames.length - 1];
    // 请求示例
    var client = initVodClient('LTAITldlbkDhCEVv','x7hE3GZFzmJkvkjdbWu9lkp78hoq6A');
    client.request("CreateUploadVideo", {
        Title: filename,
        FileName: guid() + '.' + suffix
    }, {}).then(function (response) {
        /**console.log('VideoId = ' + response.VideoId);
        console.log('UploadAddress = ' + response.UploadAddress);
        console.log('UploadAuth = ' + response.UploadAuth);
        console.log('RequestId = ' + response.RequestId); */
        res.json({
          code: 100,
          data: response
        });
    }).catch(function (response) {
        /**console.log('ErrorCode = ' + response.data.Code);
        console.log('ErrorMessage = ' + response.data.Message);
        console.log('RequestId = ' + response.data.RequestId); */
        res.json({
          code: 500,
          data: response
        });
    });
  });

  //刷新上传视频凭证
  app.get(`${namespace.root}/refreshUploadOssVoucher`, function(req, res) {
    let videoId = req.query.videoId;
    // 请求示例
    var client = initVodClient('LTAITldlbkDhCEVv','x7hE3GZFzmJkvkjdbWu9lkp78hoq6A');
    client.request("RefreshUploadVideo", {
      VideoId: videoId
    }, {}).then(function (response) {
      res.json({
        code: 100,
        data: response
      });
    }).catch(function (response) {
      res.json({
        code: 500,
        data: response
      });
    });
  });

  //获取播放凭证
  app.get(`${namespace.root}/getPlayInfo`, function(req, res) {
    let videoId = req.query.videoId;
    // 请求示例
    var client = initVodClient('LTAITldlbkDhCEVv','x7hE3GZFzmJkvkjdbWu9lkp78hoq6A');
    client.request("GetPlayInfo", {
        VideoId: videoId
    }, {}).then(function (response) {
        // play url
        if (response.PlayInfoList && response.PlayInfoList.PlayInfo && response.PlayInfoList.PlayInfo.length > 0){
            for (var i = 0; i < response.PlayInfoList.PlayInfo.length; i++){
                console.log("PlayInfo.PlayURL = " + response.PlayInfoList.PlayInfo[i].PlayURL);
            }
        }
        // base metadata
        if (response.VideoBase){
            console.log('VideoBase.Title = ' + response.VideoBase.Title);
        }
        res.json({
          code:100,
          data:response.PlayInfoList.PlayInfo
        });
    }).catch(function (response) {
      res.json({
        code:500,
        data:response
      });
    });
  });

  //获取视频信息
  app.get(`${namespace.root}/getVideoInfo`, function(req, res) {
    let videoId = req.query.videoId;
    // 请求示例
    var client = initVodClient('LTAITldlbkDhCEVv','x7hE3GZFzmJkvkjdbWu9lkp78hoq6A');
    client.request("GetVideoInfo", {
        VideoId: videoId
    }, {}).then(function (response) {
        res.json({
          code:100,
          data:response
        });
    }).catch(function (response) {
      res.json({
        code:500,
        data:response
      });
    });
  });

  //截取视频第一帧为图片
  app.get(`${namespace.root}/submitSnapshotJob`, function(req, res) {
    let videoId = req.query.videoId;
    // 请求示例
    var client = initVodClient('LTAITldlbkDhCEVv','x7hE3GZFzmJkvkjdbWu9lkp78hoq6A');
    client.request("SubmitSnapshotJob", {
        VideoId: videoId,
        SpecifiedOffsetTime:1
    }, {}).then(function (response) {
        res.json({
          code:100,
          data:response
        });
    }).catch(function (response) {
      res.json({
        code:500,
        data:response
      });
    });
  });

  //查看所有截取数据
  app.get(`${namespace.root}/listSnapshots`, function(req, res) {
    let videoId = req.query.videoId;
    // 请求示例
    var client = initVodClient('LTAITldlbkDhCEVv','x7hE3GZFzmJkvkjdbWu9lkp78hoq6A');
    client.request("ListSnapshots", {
        VideoId: videoId
    }, {}).then(function (response) {
        res.json({
          code:100,
          data:response
        });
    }).catch(function (response) {
      res.json({
        code:500,
        data:response
      });
    });
  });

  app.get(`${namespace.root}/test_upload`, async function (req, res) {
    
    res.render('test_upload', {

    });
  });
};